package com.play.ballen.home.vm

import com.play.ballen.R
import com.play.ballen.config.BallenConfig
import com.play.ballen.network.ApiRepository
import com.play.ballen.network.BallenRxHelper
import com.yuven.appframework.busevent.SingleLiveEvent
import com.yuven.appframework.network.RxSchedulerHelper
import com.yuven.appframework.util.Md5Util
import com.yuven.appframework.util.addToDisposable
import com.yuven.baselib.component.viewmodel.BaseViewModel
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.ResourceUtil

class PlayCountVM : BaseViewModel() {

    private val model = ApiRepository()
    val actionUploadStepSuccess = SingleLiveEvent<Void>()

    fun taskSubmit(num: Int) {
        showDialog.setValue(true, ResourceUtil.getString(R.string.loading), false)

        val map = mutableMapOf<String, Any>()
        val time = (System.currentTimeMillis() / 1000).toInt()  //php要求10位长度时间戳
        val signStr = "$time-$num${BallenConfig.TASK_SALT_VALUE}"
        val sign = Md5Util.stringToMD5(signStr) ?: ""

        map["num"] = num
        map["time"] = time
        map["sign"] = sign
        model.taskSubmit(map)
            .onErrorResumeNext(BallenRxHelper.HttpErrorHandleFunc())
            .compose(BallenRxHelper.transformResponse())
            .compose(RxSchedulerHelper.io_main())
            .doFinally {
                showDialog.setValue(false)
            }
            .subscribe({ data ->
                Logger.i("PlayCountVM.taskSubmit success")
                toastLiveData.value = ResourceUtil.getString(R.string.play_count_submit_success)
                actionUploadStepSuccess.call()
            }, { throwable ->
                toastLiveData.value = throwable.message
                Logger.i("PlayCountVM.taskSubmit error,msg = ${throwable.message}")
            }).addToDisposable(compositeDisposable)
    }

}